# !/usr/bin/python
# -*- coding: utf-8 -*-

from ftplib import FTP
from datetime import datetime
from common.conf_handle import myconf
from common.loger_handler import mylog

class LinkFTP:
    """
    连接 FTP 服务器
    """

    def __init__(self):

        host = myconf.get("sdcard", "host")
        port = int(myconf.get("sdcard", "port"))
        username = myconf.get("sdcard", "username")
        password = myconf.get("sdcard", "password")
        ftp_ = FTP()
        ftp_.connect(host, port)   # 连接
        ftp_.login(username, password)  # 登录
        mylog.info(f"{host} {port} {username} {password} 连接成功")
        self.ftp = ftp_
        self.buffer_size = 2048

    def download_file(self, remote_path: str, local_path: str) -> None:
        """
        从 ftp 下载文件
        :param remote_path: 远程服务器的目录绝对路径
        :param local_path:
        :return:
        """
        with open(local_path, 'wb') as fp:
            self.ftp.retrbinary('RETR ' + remote_path, fp.write, self.buffer_size)
            self.ftp.set_debuglevel(0)

    def upload_file(self, remote_path: str, local_path: str) -> None:
        """
        从本地上传文件到 ftp
        :param remote_path: 远程服务器的目录绝对路径
        :param local_path:
        :return:
        """
        with open(local_path, 'rb') as fp:
            self.ftp.storbinary('STOR ' + remote_path, fp, self.buffer_size)
            self.ftp.set_debuglevel(0)

    def path_list(self, path):
        """返回目录下所有文件名"""
        self.ftp.cwd(path)
        dri_list: list = self.ftp.nlst()
        dri_list.sort()
        return dri_list

    def delete_all_photo(self, path):
        text_list = self.path_list(path)
        for i in text_list:
            try:
                self.ftp.delete(F"{path}{i}")
            except Exception:
                pass

    def get_latest_item(self,data_list):
        """获取最新文件名称"""
        # 定义一个字典来存储文件名和对应的时间戳
        items_with_timestamps = []

        # 遍历列表，提取时间戳并存储
        for item in data_list:
            # 尝试提取时间戳部分
            parts = item.split('_')
            if len(parts) > 1:
                timestamp_str = parts[-1]
                try:
                    # 将时间戳字符串转换为datetime对象
                    timestamp = datetime.strptime(timestamp_str, "%Y%m%d%H%M%S")
                    items_with_timestamps.append((item, timestamp))
                except ValueError:
                    # 如果时间戳格式不匹配，跳过该文件
                    continue

        # 按照时间戳从新到旧排序
        items_with_timestamps.sort(key=lambda x: x[1], reverse=True)

        # 返回最新的文件名
        return items_with_timestamps[0][0] if items_with_timestamps else None

    def count_files_in_folder(self, directory):
        """获取文件夹下视频和照片数量"""
        file_types = {'.mp4': 0, '.jpg': 0}
        self.ftp.cwd(directory)
        files = []
        self.ftp.retrlines('LIST', files.append)
        for file in files:
            parts = file.split()
            if len(parts) >= 8 and not parts[-1].endswith('/'):
                filename = parts[-1]
                extension = filename.split('.')[-1].lower()
                if extension in ['mp4', 'jpg']:
                    file_types['.' + extension] += 1
        return file_types



def total_p_v():
    """获取照片数量和视频数量"""
    P = LinkFTP()
    path = myconf.get("sdcard", "photo_path")
    video_list = P.path_list(path)
    name = P.get_latest_item(video_list)
    total = P.count_files_in_folder(F"{path}{name}")
    return total



# total=total_p_v()
# print(total)